package com.jiazhong.servlet.s11.controller;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collection;

@MultipartConfig
@WebServlet("/upload")
public class FileUploadController extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        System.out.println("开始文件上传");
        // 获取到所有上传的文件
        Collection<Part> parts = request.getParts();
        for (Part part : parts) {
            String submittedFileName = part.getSubmittedFileName();
            File descFile = new File("/Users/dailyblue/workspace/io/" + submittedFileName);
            if (!descFile.getParentFile().exists()) {
                descFile.getParentFile().mkdir();
            }
            part.write("/Users/dailyblue/workspace/io/" + submittedFileName);
        }
        response.sendRedirect("index.html");

    }
}
